<template>
  <div class="all-address-container">
    <!-- 顶部导航栏 -->
    <van-nav-bar title="地址管理" left-text="返回" fixed left-arrow @click-left="$router.back()" />
    <!-- 地址列表 -->
    <van-address-list :list="list" default-tag-text="默认" @add="$router.push('/addaddress')" @edit="onEdit" v-model="chosenAddressId" />
    <van-empty description="没有地址数据" v-if="list.length == 0" />
  </div>
</template>

<script>
import axios from '@/utils/request/request'
import { Notify } from 'vant'
export default {
  name: 'allAddress',
  data() {
    return { list: [], chosenAddressId: '' }
  },
  methods: {
    // 获取用户收货地址
    async getAllAddress() {
      this.$toast.loading({
        duration: 0,
        message: '加载中...'
      })
      try {
        const data = await axios.get('/user/address/list')
        if (data.code === 0) {
          this.list = data.data.map((item) => {
            if (item.status === 1) {
              this.chosenAddressId = item.id
              return {
                id: item.id,
                tel: item.phone,
                name: item.name,
                address: item.province + item.city + item.country + item.address,
                isDefault: true
              }
            } else {
              return {
                id: item.id,
                tel: item.phone,
                name: item.name,
                address: item.province + item.city + item.country + item.address,
                isDefault: false
              }
            }
          })
          Notify({ type: 'success', message: data.msg, duration: 1000 })
        } else if (data.code === 403 || data.msg === '身份验证失败') {
          Notify({
            type: 'danger',
            message: data.msg,
            duration: 1000,
            onClose: () => {
              localStorage.removeItem('user_token')
              this.$router.replace('/login')
            }
          })
        } else {
          Notify({ type: 'danger', message: data.msg, duration: 1000 })
        }
      } catch {
        Notify({ type: 'danger', message: '请求失败！', duration: 1000 })
      } finally {
        this.$toast.clear()
      }
    },
    onEdit(address) {
      this.$router.push('/editaddress/' + address.id)
    }
  },
  created() {
    this.getAllAddress()
  }
}
</script>

<style lang="less" scoped>
.all-address-container {
  background-color: #f5f5f5;
  min-height: 100vh;
  padding-top: 46px;
  ::v-deep .van-nav-bar .van-icon,
  ::v-deep .van-nav-bar__text {
    color: #323232;
  }
}
</style>
